<template>
  <div id="app">
    <div class="order-practice-page">
      <!-- 顶部导航栏 -->
      <el-header class="navbar">
        <div class="logo">思不罔学习平台</div>
        <el-menu mode="horizontal" :default-active="activeMenu" @select="handleSelect">
          <el-menu-item index="1" @click="goBackHome">首页</el-menu-item>
          <el-menu-item index="2" @click="goToPersonal">个人中心</el-menu-item>
          <el-menu-item index="3" @click="goToCollection">我的收藏</el-menu-item>
        </el-menu>
        <div class="auth-buttons">
          <el-button link @click="goToLogin">退出登录</el-button>
        </div>
      </el-header>

      <!-- 主体内容 -->
      <el-main class="practice-content">
        <h2 class="section-title">随机练习</h2>
        <el-card shadow="hover" class="beautiful-practice-card">
          <div class="practice-intro">
            <p>🧠 随机练习题目，提升思维反应能力，查缺补漏。</p>
          </div>
          <el-button class="start-button" type="primary" @click="startPractice">
            <i class="fas fa-play-circle"></i> 开始练习
          </el-button>
        </el-card>
      </el-main>

      <!-- 题目弹窗 -->
      <el-dialog
          v-model="dialogVisible"
          title="题目练习"
          width="800px"
          :close-on-click-modal="false"
          :before-close="handleDialogClose"
          custom-class="custom-dialog"
      >
        <div v-if="currentQuestion" class="question-block">
          <div class="question-header">
            <div class="question-number">第 {{ currentQuestionIndex + 1 }} 题</div>
            <div class="question-type">
              {{ currentQuestion.questionType === 'choice' ? '选择题' : '填空题' }}
            </div>
          </div>


          <div class="question-content">
            {{ currentQuestion.content }}
          </div>

          <!-- 选择题选项（已修改为左对齐且在题目下方） -->
          <div class="options-container" v-if="currentQuestion.questionType === 'choice'">
            <el-radio-group v-model="selectedAnswer" class="radio-options-group">
              <el-radio
                  v-for="(option, index) in currentQuestion.questionChoicesList.slice(0, 4)"
                  :key="option.choiceId"
                  :label="getOptionLabel(option.choiceContent)"
                  class="option-item"
              >
                {{ option.choiceContent }}
              </el-radio>
            </el-radio-group>
          </div>

          <!-- 填空题 -->
          <div class="fill_in-container" v-if="currentQuestion.questionType === 'fill_in'">
            <el-input
                v-model="selectedAnswer"
                placeholder="请输入答案。"
                clearable
            />
          </div>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <div class="action-buttons-full">
              <div class="left-buttons">
                <el-button
                    v-if="currentQuestion"
                    link
                    class="favorite-btn"
                    @click="toggleFavorite"
                    title="收藏/取消收藏"
                >
                  <svg
                      :fill="isCollected ? '#ffb600' : '#ccc'"
                      width="24"
                      height="24"
                      viewBox="0 0 24 24"
                  >
                    <path d="M12 .587l3.668 7.568 8.332 1.151-6.064 5.828 
                    1.416 8.279-7.432-3.907-7.432 3.907 1.416-8.279-6.064-5.828 
                    8.332-1.151z" 
                    stroke="none" 
                    stroke-width="0" 
                    fill-rule="evenodd"
                    transform="scale(0.9) translate(1.2, 1)"
                  />
                </svg>
                </el-button>


                <el-button @click="prevQuestion" :disabled="currentQuestionIndex === 0">
                  <i class="fas fa-arrow-left"></i> 上一题
                </el-button>
                <el-button @click="nextQuestion" :disabled="currentQuestionIndex >= questions.length - 1">
                  下一题 <i class="fas fa-arrow-right"></i>
                </el-button>
              </div>

              <div class="right-buttons">
                <el-button @click="dialogVisible = false">关闭</el-button>
                <el-button type="primary" @click="submitAnswer">提交答案</el-button>
              </div>
            </div>
          </div>

          <!-- 正确答案展示 -->
          <div v-if="showCorrectAnswer" class="correct-answer">
            <i class="fas fa-check-circle"></i> 正确答案：<strong>{{ currentQuestion.answer }}</strong>

            <!-- 总回答次数 -->
            <div class="answer-stats">
              总回答次数：<strong>{{ currentQuestion.answerTotal || 0 }}</strong>
            </div>

            <!-- 正确率 -->
            <div class="answer-stats">
              正确率：<strong>{{ currentQuestion.correctRate }}</strong>
            </div>
          </div>


          <!-- 评论区 -->
          <div class="comments-section">
            <h3><i class="fas fa-comments"></i> 题目评论</h3>

            <!-- 评论列表滚动区域 -->
            <div class="comment-list-wrapper">
              <div v-if="comments && comments.length > 0" class="comments-list">
                <div
                    v-for="(comment, idx) in comments"
                    :key="idx"
                    class="comment-item"
                >
                  <div class="comment-author">
                    <i class="fas fa-user-circle"></i> {{ comment.author }}
                  </div>
                  <div class="comment-content">
                    {{ comment.content }}
                  </div>
                  <div class="comment-like">
                    <el-button
                        link
                        class="like-btn"
                        @click="toggleLike(comment)"
                        title="点赞 / 取消点赞"
                    >
                      <svg
                          width="20"
                          height="20"
                          viewBox="0 0 24 24"
                          :fill="comment.hasLiked ? '#f56c6c' : '#ccc'"
                      >
                        <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5
               2 6.01 4.01 4 6.5 4c1.74 0 3.41 1.01 4.13 2.44h1.74C14.09 5.01 15.76 4 17.5 4
               19.99 4 22 6.01 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                      </svg>
                      <span style="margin-left: 4px">{{ comment.likeCount }}</span>
                    </el-button>
                    <!-- 删除按钮（当前用户是作者或管理员才显示） -->
                    <el-button
                        v-if="comment.userId === currentUserId || isAdmin"
                        link
                        class="delete-btn"
                        @click.stop="deleteComment(comment.commentId)"
                        title="删除评论"
                    >
                      <svg
                          width="20"
                          height="20"
                          viewBox="0 0 24 24"
                          fill="#f56c6c"
                      >
                        <path d="M3 6h18v2H3V6zm2 3h14v13H5V9zm3 3v7h2v-7H8zm4 0v7h2v-7h-2zm4 0v7h2v-7h-2z"/>
                      </svg>
                      <span style="margin-left: 4px">删除</span>
                    </el-button>
                  </div>

                </div>
              </div>

              <div v-else class="no-comments">
                <p>暂无评论，快来发表你的见解！</p>
              </div>
            </div>

            <!-- 输入框和按钮 -->
            <el-input
                v-model="newComment"
                placeholder="写下你的评论..."
                type="textarea"
                :rows="3"
                class="new-comment-input"
            />
            <el-button
                type="primary"
                class="submit-comment-btn"
                @click="submitComment"
            >
              <i class="fas fa-paper-plane"></i> 提交评论
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from '@/api/server';
import { useUserStore } from '../store/useUserstore';

const router = useRouter();
const activeMenu = ref('1');
const dialogVisible = ref(false);
const currentQuestionIndex = ref(0);
const selectedAnswer = ref('');
const currentQuestion = ref(null);
const showCorrectAnswer = ref(false);
const questions = ref([]);
const comments = ref([]);
const newComment = ref('');
const currentUserId = ref(null);
const isAdmin = ref(false);
const fullQuestionList = ref([]);
const pageSize = 10;
const currentPage = ref(1);
const progressCache = ref({});
const STORAGE_KEY = 'practiceProgress';

const isCollected = computed(() => currentQuestion.value?.isCollected);

const saveProgress = (cache) => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(cache));
};

const getOptionLabel = (content) => {
  return content; // 或你的处理逻辑
};

// 随机打乱数组函数
const shuffleArray = (array) => {
  const newArray = [...array];
  for (let i = newArray.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
  }
  return newArray;
};

const startPractice = async () => {
  try {
    await ElMessageBox.confirm(
        '是否重新开始随机刷题？\n选择"是"将清空之前的做题记录，选择"否"继续之前的进度。',
        '重新开始确认',
        {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }
    );
    localStorage.removeItem(STORAGE_KEY);
    progressCache.value = {};
  } catch (e) {
    // 用户取消，保留进度
  }

  try {
    const majorRes = await axios.get('/users/majors/myinfo');
    const majorId = majorRes.data.data.majorId;

    const res = await axios.get('/question/list', {
      params: {
        majorId: majorId
      }
    });

    console.log('测试', res.data.data);

    const data = res.data.data;
    if (!data || data.length === 0) {
      ElMessage.warning('题目列表为空');
      return;
    }

    // 随机打乱题目顺序
    const shuffledData = shuffleArray(data);

    fullQuestionList.value = shuffledData.map(q => {
      const cached = progressCache.value[q.questionId] || {};
      return {
        ...q,
        userAnswer: cached.userAnswer || '',
        hasShownAnswer: cached.hasShownAnswer || false,
      };
    });

    currentPage.value = 1;
    loadCurrentPageQuestions();
  } catch (err) {
    ElMessage.error('题目加载失败');
  }
};

const loadCurrentPageQuestions = async () => {
  const start = (currentPage.value - 1) * pageSize;
  const end = start + pageSize;

  // 随机选取题目，而不是按顺序
  const availableQuestions = fullQuestionList.value.filter(q =>
      !progressCache.value[q.questionId]?.hasShownAnswer
  );

  if (availableQuestions.length === 0) {
    // 如果所有题目都做过了，从全部题目中随机选取
    questions.value = shuffleArray(fullQuestionList.value).slice(0, pageSize);
  } else {
    // 优先选取未做过的题目
    const remainingQuestions = shuffleArray(availableQuestions).slice(0, pageSize);
    // 如果未做过的题目不足，补充已做过的题目
    if (remainingQuestions.length < pageSize) {
      const answeredQuestions = shuffleArray(
          fullQuestionList.value.filter(q =>
              progressCache.value[q.questionId]?.hasShownAnswer
          )
      ).slice(0, pageSize - remainingQuestions.length);
      questions.value = [...remainingQuestions, ...answeredQuestions];
    } else {
      questions.value = remainingQuestions;
    }
  }

  if (questions.value.length > 0) {
    currentQuestionIndex.value = 0;
    currentQuestion.value = questions.value[0];
    await loadComments();
    selectedAnswer.value = currentQuestion.value.userAnswer || '';
    showCorrectAnswer.value = currentQuestion.value.hasShownAnswer || false;
    dialogVisible.value = true;
  } else {
    ElMessage.warning('没有更多题目了');
  }
};

const submitAnswer = async () => {
  const userAnswer = selectedAnswer.value.trim();
  const question = currentQuestion.value;

  if (!userAnswer) {
    ElMessage.warning('请选择或填写答案');
    return;
  }

  try {
    const res = await axios.post('/question/submit', {
      questionId: question.questionId,
      submitAnswer: userAnswer.split('.')[0].trim()
    });

    if (res.data.code !== 1) {
      ElMessage.error(res.data.msg || '提交失败，服务器返回异常状态');
      return;
    }

    const responseData = res.data.data;
    if (!responseData) {
      ElMessage.error('服务器返回数据格式异常');
      return;
    }

    question.userAnswer = userAnswer;
    question.hasShownAnswer = true;
    question.answer = responseData.correctAnswer || question.answer;
    question.isCorrect = responseData.isCorrect;

    progressCache.value[question.questionId] = {
      ...(progressCache.value[question.questionId] || {}),
      userAnswer: userAnswer,
      hasShownAnswer: true,
      isCollected: question.isCollected || false,
      isCorrect: responseData.isCorrect
    };
    saveProgress(progressCache.value);

    showCorrectAnswer.value = true;
    ElMessage[responseData.isCorrect ? 'success' : 'error'](
        responseData.message || (responseData.isCorrect ? '回答正确！' : '回答错误')
    );

    if (process.env.NODE_ENV === 'development') {
      console.log('提交详情:', {
        questionId: question.questionId,
        userAnswer,
        serverResponse: responseData,
        correctAnswer: question.answer
      });
    }
  } catch (e) {
    console.error('提交答案出错:', e);
    ElMessage.error(`提交失败: ${e.response?.data?.message || e.message || '网络错误'}`);
  }
};

const toggleFavorite = async () => {
  const question = currentQuestion.value;
  const userStore = useUserStore();

  const userInfoStr = localStorage.getItem('userInfo');
  if (userInfoStr) {
    const userInfo = JSON.parse(userInfoStr);
    userStore.setUserInfo(userInfo);
  }

  if (!question) return;

  try {
    await axios.post(`/users/favorite/${question.questionId}`);
    question.isCollected = !question.isCollected;
    ElMessage.success(question.isCollected ? '题目已收藏' : '已取消收藏');
  } catch {
    ElMessage.error('操作失败，请稍后再试');
  }
};

const nextPage = () => {
  ElMessageBox.confirm('是否继续下一页的随机练习？', '继续确认', {
    confirmButtonText: '继续',
    cancelButtonText: '取消',
    type: 'info',
  }).then(() => {
    currentPage.value++;
    loadCurrentPageQuestions();
  }).catch(() => {
    ElMessage.info('已取消继续练习');
  });
};

const submitComment = async () => {
  const token = localStorage.getItem('token');
  const userInfoString = localStorage.getItem('userInfo');
  const userId = userInfoString ? JSON.parse(userInfoString)?.userId : null;

  if (!token || !userId) {
    ElMessage.warning('请先登录后再评论');
    router.push('/');
    return;
  }

  if (!newComment.value.trim()) {
    ElMessage.warning('评论不能为空');
    return;
  }

  try {
    await axios.post('/users/comments/add', {
      questionId: currentQuestion.value.questionId,
      content: newComment.value.trim()
    });

    ElMessage.success('评论成功');
    newComment.value = '';
    await loadComments();
  } catch {
    ElMessage.error('评论失败');
  }
};

const deleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm('确定要删除该评论吗？', '删除确认', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    });

    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.warning('请先登录');
      router.push('/');
      return;
    }

    await axios.delete(`/users/comments/delete/${commentId}`, {
      headers: { Authorization: `Bearer ${token}` }
    });

    ElMessage.success('评论删除成功');
    await loadComments();
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('评论删除失败');
    }
  }
};

const loadComments = async () => {
  const userInfoStr = localStorage.getItem('userInfo');
  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr);
      currentUserId.value = userInfo.userId;
      isAdmin.value = userInfo.isAdmin || false;
    } catch {
      currentUserId.value = null;
      isAdmin.value = false;
    }
  }

  try {
    const res = await axios.get(`/users/comments/get/${currentQuestion.value.questionId}`);
    const commentList = res.data.data || [];

    let likedCommentIds = [];
    const token = localStorage.getItem('token');
    let likeCountList = [];

    if (token) {
      const likeRes = await axios.get(`/users/commentlike/list/${currentQuestion.value.questionId}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      likedCommentIds = likeRes.data.data || [];
    }

    if (token) {
      try {
        const likeCountRes = await axios.get(`/users/commentlike/count/${currentQuestion.value.questionId}`, {
          headers: {
            Authorization: `Bearer ${token}`
          }
        });
        likeCountList = likeCountRes.data.data || [];
      } catch (e) {
        console.warn('获取点赞数量失败', e);
      }
    }

    for (const comment of commentList) {
      comment.hasLiked = likedCommentIds.includes(comment.commentId);
      comment.likeCount = likeCountList.find(item => item.commentId === comment.commentId)?.likeCount || 0;
    }

    comments.value = commentList;
  } catch {
    comments.value = [];
  }
};

const toggleLike = async (comment) => {
  const token = localStorage.getItem('token');
  const userInfoString = localStorage.getItem('userInfo');
  const userId = userInfoString ? JSON.parse(userInfoString)?.userId : null;

  if (!token || !userId) {
    ElMessage.warning('请先登录后再点赞');
    router.push('/');
    return;
  }

  try {
    await axios.post(`/users/commentlike/${comment.commentId}`, null, {
      headers: { Authorization: `Bearer ${token}` }
    });

    comment.hasLiked = !comment.hasLiked;
    comment.likeCount += comment.hasLiked ? 1 : -1;
    ElMessage.success(comment.hasLiked ? '点赞成功' : '取消点赞成功');
  } catch {
    ElMessage.error('操作失败，请稍后重试');
  }
};

const prevQuestion = async () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--;
    const q = questions.value[currentQuestionIndex.value];
    currentQuestion.value = q;
    selectedAnswer.value = q.userAnswer || '';
    showCorrectAnswer.value = q.hasShownAnswer || false;
    await loadComments();
  }
};

const nextQuestion = async () => {
  if (currentQuestionIndex.value < questions.value.length - 1) {
    currentQuestionIndex.value++;
    const q = questions.value[currentQuestionIndex.value];
    currentQuestion.value = q;
    selectedAnswer.value = q.userAnswer || '';
    showCorrectAnswer.value = q.hasShownAnswer || false;
    await loadComments();
  }
};

const handleSelect = (index) => console.log(index);
const goBackHome = () => router.push('/home');
const goToPersonal = () => router.push('/personal');
const goToCollection = () => router.push('/collection');
const goToLogin = async () => {
  try {
    await axios.post('/users/logout'); // 会自动带上 Bearer token
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    ElMessage.success('退出成功');
    await router.push('/');
  } catch (error) {
    console.error('退出失败：', error);
    ElMessage.error('退出失败');
  }
};
</script>


<style scoped>
@import "../styles/Practice.css";
</style>